import React, { Component, PropTypes } from 'react';
import { Router, Route } from 'react-router';
import Head from './Head';
import ScanGroup from './ScanGroup';
import PointsList from './PointsList';
import styles from './App.less';
import comm from './common.less';
import cap from './assets/cap.png';
import star from './assets/star.png';
import office from './assets/office.png';
import dietitian from './assets/dietitian.png'
import { getQueryStringByName } from '~/Util';
import Customer from '~/services/Customer';
import Loading from './Loading/Loading';
import { message } from 'antd';
import AccruePoints from '~/services/Accruepoints';

class App extends Component {
  constructor(props, context) {
    super(props, context);
    const object = this.props.location.state || {};
    this.username = object.username || '营养家会员';
    this.mobilephone = object.mobilephone;
    this.isRegister = object.isRegister;
    this.userPhone = object.userPhone || '';
    object.PointList = object.PointList || [];
    const score = object.score;
    this.state = {
      PointList: object.PointList,
      length: object.PointList.length,
      Score: score,
    }
  }
  componentDidMount() {
    this.checkMember();
  }
  onSubmit = (e) => {
    if (this.state.length === 0) {
      const code = this.refs.scan.state.securityCode;
      if (code === 16) {
        this.onCallBack(code)
      }
    } else {
      location.href = 'http://www.baidu.com'
    }
  }
  /**
   * [onCallBack 扫码回调方法]
   * @param  {[type]} securityCode [产品防伪码]
   * @param  {[type]} score        [description]
   * @return {[type]}              [description]
   */
  onCallBack = (securityCode) => {
    Loading.show();
    AccruePoints.accruePoints({
      memPhone: this.mobilephone,
      userName: this.userPhone,
      fwcode: securityCode,
      barcode: '',
    }).then(data => {
      Loading.hide();
      const singleScore = parseInt(data.accruedPointsTotal, 10);
      this.setState(({ PointList, length, Score }) => {
        PointList.push({
          name: data.productName,
          score: singleScore,
        });
        return {
          length: length + 1,
          Score: data.productPointsBalance,
        }
      })
      return {
        securityCode: '',
        buttonText: '切换扫码',
      }
    }).catch(err => {
      Loading.hide();
      if (err.status === '136') {
        this.context.router.push({
          pathname: '/requirebarcode',
          state: {
            name: this.username,
            mobilephone: this.mobilephone,
            userPhone: this.userPhone,
            code: securityCode,
            PointList: this.state.PointList,
            score: this.state.Score,
            isRegister: this.isRegister,
          },
        })
      }
      const code = securityCode;
      message.error(err.errorMsg || '系统繁忙，请稍后重试');
      return {
        securityCode: code,
        buttonText: '提交',
      }
    })
  }
  checkMember = () => {
    if (!this.isRegister) {
      Loading.show();
      Customer.getMemberInfo(
        {
          code: getQueryStringByName('code'),
          state: getQueryStringByName('state'),
        }
      ).then(data => {
        const { member, openId } = data;
        if (!openId) {
          message.error('请使用微信访问');
        } else
        if (!member) {
          this.context.router.push({
            pathname: '/require',
            state: {
              userPhone: getQueryStringByName('id'),
            },
          });
        }
        Loading.hide();
      }).catch(err => {
        message.error('网络出现错误，请刷新重试');
        Loading.hide();
      })
      this.isRegister = 0;
    }
  }
  render() {
    const buttonText = this.state.length === 0 ? '提 交' : '完 成';
    const imageshow = this.state.length === 0 ? comm.hide : comm.show;
    const firstimage = this.state.length === 0 ? comm.show : comm.hide;
    return <div>
             <Head Name={this.username} Phone={this.mobilephone}
               length={this.state.length} Score={this.state.Score}
             />
             <PointsList points={this.state.PointList} />
             <ScanGroup callback={this.onCallBack} ref="scan" placeholder="请输入16位产品防伪码" />
             <div className={comm.textcenter}>
               <button className={styles.finishButton} onClick={this.onSubmit}>{buttonText}</button>
             </div>
             <div className={`${imageshow} ${comm.textcenter}`}>
               <img src={star} className={styles.finishImage} />
             </div>
             <div className={`${firstimage} ${comm.textcenter}`}>
               <img src={cap} className={styles.image} />
             </div>
             <div className={`${imageshow} ${comm.textcenter}`}>
               <a href="http://www.baidu.com">
                 <img src={office} className={styles.image} />
               </a>
             </div>
             <div className={`${imageshow} ${comm.textcenter}`}>
               <img src={dietitian} className={styles.image} />
             </div>
           </div>
  }
}

App.propTypes = {
};
App.contextTypes = {
  router: PropTypes.object,
}

export default App;
